<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showDialogByAdd">添加</el-button>
      </div>
    </template>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="trademarkList" border style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="180" />
      <el-table-column prop="logoUrl" align="center" label="品牌LOGO">
        <template v-slot="{row}">
          <img style="width:100px;" :src="row.logoUrl" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{row}">
          <el-button title="编辑" type="warning" :icon="Edit" size="small" @click="showDialogByEdit(row)"></el-button>
          <el-button title="删除" type="danger" :icon="Delete" size="small" @click="showDialogByDelete(row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination style="margin-top:10px" v-model:currentPage="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 20]" :small="small" :disabled="disabled" :background="background" layout="prev, pager, next, jumper,->,sizes,total " :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加或更新品牌时的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="`${trademarkInfo.id?'更新':'添加'}品牌`">
      <el-form :model="trademarkInfo" ref="ruleFormRef" :rules="rules">
        <el-form-item label="品牌名称" label-width="90px" prop="tmName">
          <el-input style="width:80%" v-model="trademarkInfo.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="90px" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/fileUpload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                图片只能上传.jpg/png等格式,且大小不能超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
        </span>
      </template>

    </el-dialog>
  </el-card>
</template>


<script lang="ts">
// 上面这种是来书写组件名称
export default {
  name: 'Trademark'
};
</script>

<script lang="ts" setup>
// 后续其它业务逻辑 在语法糖的这个结构当中来书写
import { onMounted, reactive, ref } from 'vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { reqGetTrademarkInfoData, reqAddTrademarkInfoData, reqDeleteTrademarkInfoData, reqUpdateTrademarkInfoData } from '@/api/product/trademark';
import type { TrademarkListModel, TrademarkModel } from '@/api/product/model/trademarkModel';
import type { UploadProps } from 'element-plus';
// 表单校验
import type { FormInstance, FormRules } from 'element-plus';

const ruleFormRef = ref<FormInstance>();
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示的条数
const total = ref(0); // 商品总数量
// 将当前的这个数组使用ref的方式来定义响应式 因为通过.value的方式赋值不影响响应式功能
// .value的值刚好是一个Proxy格式的数据
const trademarkList = ref<TrademarkListModel>([]);
const initTrademark = () => ({ tmName: '', logoUrl: '' });
const trademarkInfo = reactive<TrademarkModel>(initTrademark());
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const loading = ref(true);

// console.log('mm',import.meta.env)
const BASE_URL = import.meta.env.VITE_API_URL;

// 弹出对话框及上传图片时的变量值
const dialogFormVisible = ref<boolean>(false);

const imageUrl = ref('');

// 1. 定义一个获取分页数据的功能方法
const getTrademarkInfoData = async () => {
  // const result = await reqGetTrademarkInfoData(1, 5);
  const result = await reqGetTrademarkInfoData(currentPage.value, pageSize.value);
  // console.log('tm', result);
  trademarkList.value = result.records;

  total.value = result.total;

  loading.value = false; // 隐藏loading效果
};

// 2. 在钩子函数当中执行调用
onMounted(() => {
  getTrademarkInfoData();
});

// 4. 每页显示多少条触发的时候，也要重新渲染页面
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为1
  getTrademarkInfoData();
};

// 3. 页码发生变化的时候 重新发送请求
const handleCurrentChange = (val: number) => {
  currentPage.value = val;

  getTrademarkInfoData();
};

// 图片上传相关

// 6.添加图片成功后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log(response, uploadFile);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademarkInfo.logoUrl = response.data;
  // 清除之前的图片校验规则
  ruleFormRef.value?.clearValidate(['logoUrl']);
};

// 5.图片上传之前的格式校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  const imgArr = ['image/jpeg', 'image/png', 'image/jpg'];
  if (!imgArr.includes(rawFile.type)) {
    ElMessage.error('图片格式不正确,应该是.jpg/.png/.jpeg等');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M,请重新上传...');
    return false;
  }
  return true;
};

// 7.实现品牌上传
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    console.log('form', valid, fields);
    if (valid) {
      if (trademarkInfo.id) {
        await reqUpdateTrademarkInfoData(trademarkInfo);
        ElMessage.success('品牌更新成功');
      } else {
        await reqAddTrademarkInfoData(trademarkInfo);
        // ElMessage.success('品牌上传成功')
        ElMessage({
          type: 'success',
          message: '品牌上传成功'
        });
        currentPage.value = 1;
      }
      // 隐藏对话框
      dialogFormVisible.value = false;

      // 刷新一下页面 所谓刷新页面，就是重新发送 请求 获取一下最新的数据

      getTrademarkInfoData();
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 8.删除品牌时的弹框
const showDialogByDelete = (id: number) => {
  ElMessageBox.confirm('您确定要删除此条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDeleteTrademarkInfoData(id);
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
      // 重新刷新页面
      getTrademarkInfoData();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      });
    });
};

// 9.编辑品牌之数据回显
const showDialogByEdit = (row: TrademarkModel) => {
  // 9.1弹框
  dialogFormVisible.value = true;
  // 9.2在弹框上显示待编辑数据
  Object.assign(trademarkInfo, row);
};

// 10.添加品牌时，清空原来的数据
const showDialogByAdd = () => {
  Object.assign(trademarkInfo, initTrademark());
  delete trademarkInfo.id;
  dialogFormVisible.value = true;

  // 清除之前的校验规则  不写参数的时候，是清空所有的校验规则
  ruleFormRef.value?.clearValidate();
};

// 11.书写校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空', trigger: 'blur' },
    { min: 2, max: 8, message: '名称长度在2--8个字符之间', trigger: 'blur' }
  ],
  logoUrl: [
    {
      required: true,
      message: '请上传一张品牌图片',
      trigger: 'change'
    }
  ]
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>